#include "util.hpp"

static void Usage(string proc)
{
    cerr << "Usage " << proc << "serverIp serverPort" << endl;
}

volatile bool quit = false;

// ./tcpClient serveIp servePort
int main(int argc, char* argv[])
{
    if (argc != 3) 
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    //创建套接字
    string serverIp = argv[1];
    uint16_t serverPort = atoi(argv[2]);
    
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        Log(FATAL, "socket:%s", strerror(errno));
        exit(SOCKET_ERR);
    }
    Log(DEBUG, "client sock create success");
    //建立链接
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverPort);
    server.sin_addr.s_addr = inet_addr(serverIp.c_str());
    if (connect(sock, (const struct sockaddr*)&server, sizeof(server)) < 0)
    {
        Log(FATAL, "connect:%s", strerror(errno));
        exit(CONN_ERR);
    }
    Log(NOTICE, "connect success");
    //开始聊天
    string message;
    while (!quit)
    {
        message.clear();
        cout <<"请输入你的消息:" << endl;
        getline(cin, message);
        if (strcasecmp("exit", message.c_str()) == 0)
        {
            quit = true;
        }
        ssize_t s = write(sock, message.c_str(), message.size());
        if (s > 0)
        {
            message.resize(1024);
            ssize_t rs = read(sock, (char*)message.c_str(), message.size() - 1);
            if (s > 0)
            {
                message[rs] = '\0';
            }
            else if (s <=  0)
            {
                cout << "quit" << endl;;
                break;
            }
            cout << "Server Echo>> " << message << endl; 
        }
        else
        {
            break;
        }
    }
    close(sock);
    return 0;
}
